package io.terminus.spzx.manager.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import io.terminus.spzx.manager.service.ValidateCodeService;
import io.terminus.spzx.model.vo.system.ValidateCodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author lichunlong lcl253137@alibaba-inc.com
 * @Desc 图片验证码Service实现类
 * @Date 2024-03-31
 */
@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public ValidateCodeVo generateValidateCode() {
        // 1、通过hutool工具生成图片验证码
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 2);

        // 4位验证码的值
        String codeValue = circleCaptcha.getCode();
        // 图片验证码的base64编码
        String imageBase64 = circleCaptcha.getImageBase64();

        // 2、存储验证码到redis
        String key = UUID.randomUUID().toString().replaceAll("-", "");
        // key: UUID; value: 图片验证码的Base64编码; 超时时长5分钟
        redisTemplate.opsForValue().set("user:validate" + key, codeValue, 5, TimeUnit.MINUTES);

        //3、返回ValidateCodeVo对象
        return new ValidateCodeVo(key, "data:image/png;base64," + imageBase64);
    }
}
